<template>
  <div class="background">
    <a-card style="margin-bottom: 10px">

      <a-row>
        <a-col :span="24">
          <a-form
            layout="inline"
            :form="form"
            @submit="handleSubmit"
          >
            <a-form-item label="样衣号">
              <a-input
                allow-clear
                placeholder="请输入样衣号"
                v-model="sampleCode"
              ></a-input>
            </a-form-item>
            <a-form-item label="是否已经有扩色数据">
              <a-select
                style="width: 180px"
                placeholder="请选择是否"
                v-model="expandColorFlag"
                allow-clear
              >
                <a-select-option value="0">
                  否
                </a-select-option>
                <a-select-option value="1">
                  是
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button
                type="primary"
                html-type="submit"
              >搜索</a-button>
              <a-button
                style="margin-left:10px"
                type="primary"
                ghost
                @click="toPrint"
              >打印</a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-card>
    <a-card>
      <a-table
        bordered
        :loading="loading"
        :pagination="pagination"
        :columns="columns"
        :data-source="dataSource"
        @change="handleTableChange"
        :row-selection="{ selectedRowKeys: selectedRowKeys,selectedRows:selectedRows, onChange: onSelectChange}"
        :scroll="{ x: true }"
      >
        <template
          slot="action"
          slot-scope="txt, record"
        >
        <a
            class="mr-10"
            @click="toDetail(record)"
          >
            查看
          </a>
          <a
            class="mr-10"
            @click="tosubmit(record)"
          >
            提交
          </a>
        </template>
      </a-table>
      <a-modal
        v-model="showError"
        title="错误信息"
        footer=''
      >
        <a-table
          bordered
          :pagination="false"
          :columns="inncolumns"
          :data-source="errorList"
          :scroll="{ x: true }"
        >
        </a-table>
      </a-modal>
      <a-modal
        v-model="showSuccess"
        title="提示信息"
        footer=''
      >
        <p>扩色单据:{{extendColorBillNo}}</p>
        <a-table
          bordered
          :pagination="false"
          :columns="billC"
          :data-source="invokingBillList"
          :scroll="{ x: true }"
        >
        </a-table>
      </a-modal>
      <a-modal
        v-model="visible"
        title="输入代料号"
        @ok="handleOk"
      >
        <a-input
          placeholder="请输入代料号"
          v-model="replaceMaterialCode"
        />
      </a-modal>
      <a-modal
        v-model="visibleRe"
        title="输入代料号"
        @ok="handleOk"
      >
        <a-input
          placeholder="请输入代料号"
          v-model="replaceMaterialCode"
        />
      </a-modal>
      <a-modal
        v-model="visibleIn"
        title="输入调料单数量"
        @ok="handleOkIn"
      >
        <a-input
          placeholder="请输入调料单数量"
          v-model="invokingCount"
        />
      </a-modal>
      <printList
        v-if="showPrint"
        :content="selectedRows"
        @closePrint="closePrint"
      ></printList>
       <detailInfo
        v-if="showDetail"
        :content="content"
        @closeDetail="closeDetail"
      ></detailInfo>
      
    </a-card>
  </div>
</template>

<script>
import { postAction } from '@/api/manage'
import printList from './print.vue'
import detailInfo from './detail.vue'
import { materialStock } from '@api/e-product/index.js'
const billC = [
  {
    title: '调料单据',
    dataIndex: 'invokingBillNo',
  },
  {
    title: '物料编码',
    dataIndex: 'materialCode',
  },
  {
    title: '消息',
    dataIndex: 'msg',
  },
]
const inncolumns = [
  {
    title: '颜色',
    dataIndex: 'color',
  },
  {
    title: '面料号',
    dataIndex: 'materialCode',
  },
  {
    title: '代料号',
    dataIndex: 'replaceMaterialCode',
  },
  {
    title: '错误信息',
    dataIndex: 'msg',
  },
]
const columns = [
  {
    title: '样衣号',
    width: 150,
    dataIndex: 'sampleCode',
  },
  {
    title: '品名',
    width: 120,
    dataIndex: 'designName',
  },
  {
    title: '品类',
    width: 90,
    dataIndex: 'sampleCat',
  },
  {
    title: '波段',
    width: 70,
    dataIndex: 'band',
  },
  {
    title: '面料',
    width: 150,
    dataIndex: 'materialCode',
  },
  {
    title: '颜色',
    width: 110,
    dataIndex: 'color',
  },
  {
    title: '创建日期',
    width: 150,
    dataIndex: 'createDate',
  },
  {
    title: '版次单据号',
    width: 150,
    dataIndex: 'editionBillNo',
  },
  // {
  //   title: '版次编号',
  //   width: 90,
  //   dataIndex: 'editionCode',
  // },
  {
    title: '第几件',
    width: 80,
    dataIndex: 'sortNumber',
  },
  {
    title: '操作',
    width: 100,
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  components: {
    printList,
    detailInfo
  },
  data() {
    return {
      inncolumns,
      columns,
      billC,
      form: this.$form.createForm(this),
      patt: 'api/gateway/basemgt-op',
      sampleCode: '',
      expandColorFlag: undefined,
      loading: false,
      dataSource: [],
      content:{},
      extendColorInfos: [],
      replaceMaterialCode: '',
      invokingCount: '',
      materialCodeList: [],
      invokingBillList: [],
      errorList: [],
      visible: false,
      showPrint: false,
      showSuccess: false,
      visibleIn: false,
      showError: false,
      visibleRe: false,
      showDetail:false,
      extendColorBillNo: '',
      num: 0,
      item: {},
      selectedRowKeys: [],
      selectedRows: [],
      ifFinish: false,
      record: {},
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total) => `共 ${total} 条记录`,
        itemRender: (current, type, originalElement) => {
          if (type === 'prev') {
            return <a>上一页</a>
          } else if (type === 'next') {
            return <a>下一页</a>
          }
          return originalElement
        },
      },
    }
  },
  mounted() {
    this.loadData()
  },
  computed: {
    jobNumber() {
      return this.$store.getters.userInfo.workNo || ''
    },
  },
  methods: {
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    closeError() {
      this.showError = false
    },
    toPrint() {
      if (!this.selectedRows.length) {
        this.$message.error('请先选择打印列表！')
      } else {
        this.showPrint = true
      }
    },
    closePrint() {
      this.showPrint = false
    },
    closeDetail() {
      this.showDetail = false
    },
    toDetail(record){
      this.showDetail = true
      this.content = record
    },
    handleTableChange(pagination) {
      this.pagination = pagination
      this.loadData(1)
    },
    tosubmit(record) {
      this.errorList = []
      this.record = record
      this.$confirm({
        content: '确定要提交' + record.sampleCode + '吗？',
        onOk: () => {
          const params = {
            editionBillNo: record.editionBillNo,
            editionCode: record.editionCode,
            sortNumber: record.sortNumber,
          }
          postAction(`${this.patt}/extendcolor/check/color`, params).then((res) => {
            if (res.code == 200) {
              if (!res.data.length) {
                this.checkMaterial(record)
              } else {
                this.errorList = res.data
                this.$nextTick(() => {
                  this.showError = true
                })
              }
            } else {
              this.$message.warning('接口错误')
            }
          })
        },
        onCancel() {},
      })
    },
    async checkMaterial(record) {
      this.errorList = []
      const params = {
        editionBillNo: record.editionBillNo,
        editionCode: record.editionCode,
        sortNumber: record.sortNumber,
        sampleCode: record.sampleCode,
      }
      postAction(`${this.patt}/extendcolor/check/material`, params).then(async (res) => {
        if (res.code == 200) {
          if (!res.data.length) {
            await this.seachMaterial(record)
          } else {
            this.errorList = res.data
            this.$nextTick(() => {
              this.showError = true
            })
          }
        } else {
          if (res.message) {
            this.$message.warning('接口错误')
          } else {
            this.$message.warning(res.msg)
          }
        }
      })
    },
    async seachMaterial(record, num) {
      console.log(num)
      this.item = {}
      if (!num) {
        this.materialCodeList = record.materialList
        this.item = this.materialCodeList[0]
        this.materialStock(record, this.item)
      } else {
        this.item = this.materialCodeList[num]
        this.$nextTick(() => {
          this.materialStock(record, this.item, num)
        })
      }
    },
    async materialStock(record, item, num) {
      const params = {
        editionBillNo: record.editionBillNo,
        editionCode: record.editionCode,
        sortNumber: record.sortNumber,
        materialCode: item.materialCode,
        sampleCode: record.sampleCode,
      }
      const res = await materialStock('extendcolor', params)
      if (res.code == 200) {
        if (res.data > 0) {
          this.materialCodeList.map((subitem) => {
            if (subitem.materialCode == item.materialCode) {
              subitem.ifFinish = true
            }
          })
          const newArr = this.materialCodeList.filter((item) => item.ifFinish == true)
          if (newArr.length == this.materialCodeList.length) {
            this.submit(this.record)
          } else {
            if (!num) {
              this.seachMaterial(record, 1)
            } else {
              this.seachMaterial(record, num + 1)
            }
          }
        } else {
          this.otherMaterial(record, item)
        }
      } else {
        this.$message.warning(res.msg)
      }
    },
    otherMaterial(record, item) {
      var that = this
      that.$confirm({
        content: item.replaceMaterialCode ? '面料号' + item.materialCode + '库存不足，是否启用代料号:' + item.replaceMaterialCode + '？' : '面料号' + item.materialCode + '库存不足，是否启用代料？',
        onOk: () => {
          this.materialCodeList.map((subitem) => {
            if(subitem.materialCode == item.materialCode){
              subitem.openReplaceMaterial = 10
            }
          })
          if (item.replaceMaterialCode) {
            that.seachOtherMaterial(record, item)
          } else {
            that.replaceMaterialCode = ''
            that.visible = true
            // that.item = item
            that.record = record
          }
        },
        onCancel() {
          // that.item = item
          that.invokingCount = ''
          that.visibleIn = true
        },
      })
    },
    async seachOtherMaterial(record, item) {
      const params = {
        editionBillNo: record.editionBillNo,
        editionCode: record.editionCode,
        sortNumber: record.sortNumber,
        materialCode: item.replaceMaterialCode,
        sampleCode: record.sampleCode,
      }
      const res = await postAction(`${this.patt}/extendcolor/check/material/stock`, params)
      if (res.code == 200) {
        if (res.data > 0) {
          this.materialCodeList.map((subitem) => {
            if (subitem.materialCode == item.materialCode) {
              subitem.ifFinish = true
            }
          })
          const newArr = this.materialCodeList.filter((item) => item.ifFinish == true)
          if (newArr.length == this.materialCodeList.length) {
            this.submit(this.record)
          } else {
            this.materialCodeList.map((item, index) => {
              if (this.item.materialCode == item.materialCode) {
                this.num = index + 1
              }
            })
            this.$nextTick(() => {
              this.seachMaterial(this.record, this.num)
            })
          }
        } else {
          this.replaceMa(record, item)
        }
      } else {
        this.$message.warning(res.msg)
      }
    },
    replaceMa(record, item) {
      var that = this
      that.$confirm({
        content: '代料号'+ item.replaceMaterialCode +'库存不足，是否替换代料？',
        onOk: () => {
          that.replaceMaterialCode = ''
          that.visible = true
          // that.item = item
          that.record = record
        },
        onCancel() {
          // that.item = item
          that.invokingCount = ''
          that.visibleIn = true
        },
      })
    },

    handleOk() {
      if (!this.replaceMaterialCode) {
        this.$message.warning('请输入代料号！')
      } else {
        this.visible = false
        this.item.replaceMaterialCode = this.replaceMaterialCode
        this.seachOtherMaterial(this.record, this.item)
      }
    },
    handleOkIn() {
      if (!this.invokingCount) {
        this.$message.warning('请输入调料单数量!')
      } else {
        this.materialCodeList.map((item) => {
          if (this.item.materialCode == item.materialCode) {
            item.ifFinish = true
            item.invokingCount = this.invokingCount
            item.openReplaceMaterial = 20
            item.option = 10
          }
        })
        this.$nextTick(() => {
          const newArr = this.materialCodeList.filter((item) => item.ifFinish == true)
          if (newArr.length == this.materialCodeList.length) {
            console.log(111)
            this.submit(this.record)
          } else {
            this.materialCodeList.map((item, index) => {
              if (this.item.materialCode == item.materialCode) {
                this.num = index + 1
              }
            })
            this.$nextTick(() => {
              this.seachMaterial(this.record, this.num)
            })
          }
          this.visibleIn = false
        })
      }
    },
    submit(record) {
      // console.log(this.materialCodeList);
      this.materialCodeList.map((item) => {
        if (!item.invokingCount) {
          item.option = 20
        }
        if(!item.openReplaceMaterial){
          item.openReplaceMaterial = 20
        }
      })
      const newArr = this.materialCodeList.filter((item) => {
        return delete item.ifFinish
      })
      const params = {
        editionBillNo: record.editionBillNo,
        editionCode: record.editionCode,
        sortNumber: record.sortNumber,
        jobNumber: this.jobNumber,
        sampleCode: record.sampleCode,
        extendColorInfos: newArr,
      }
      console.log(params)
      try {
        postAction(`${this.patt}/extendcolor/submit`, params).then((res) => {
          if (res.code == 200) {
            this.$message.success('提交成功！')
            this.extendColorBillNo = res.data.extendColorBillNo
            this.invokingBillList = res.data.invokingBillList
            this.$nextTick(() => {
              this.showSuccess = true
            })
          } else {
            this.$message.warning('提交失败'+res.msg)
          }
        })
      } catch (error) {
        this.$message.warning('提交失败'+error.msg)
      }
    },
    handleSubmit(e) {
      e.preventDefault()
      this.loadData()
    },
    loadData(key) {
      this.loading = true
      const params = {
        jobNumber:this.jobNumber
      }
      if (key) {
        params.current = this.pagination.current
        params.size = this.pagination.pageSize
      } else {
        params.current = 1
      }
      if (this.sampleCode) {
        params.sampleCode = this.sampleCode
      }
      if (this.expandColorFlag) {
        params.expandColorFlag = this.expandColorFlag
      }
      try {
        postAction(`${this.patt}/extendcolor/page`, params).then((data) => {
          if (data.code == 200) {
            this.dataSource = data.data.records
            this.pagination.current = data.data.current
            this.pagination.total = data.data.total
          } else {
            this.$message.warning('获取列表失败！')
          }
          this.loading = false
        })
      } catch (error) {
        this.loading = false
      }
    },
  },
}
</script>
<style lang="less" scoped>
.background {
  background: transparent;
}
.ant-modal-body {
  display: flex;
  justify-content: space-between;
}
</style>